from PySide6.QtWidgets import QWidget, QVBoxLayout, QTableWidget, QTableWidgetItem, QHeaderView
from PySide6.QtCore import Signal, Qt
import pandas as pd

class TableViewer(QWidget):
    data_updated = Signal(str, object)  # 信号：井名称和数据

    def __init__(self, well_name, parent=None):
        super().__init__(parent)
        self.well_name = well_name
        self.data = None
        layout = QVBoxLayout(self)
        self.table = QTableWidget()
        self.table.setAlternatingRowColors(True)  # 设置交替行颜色
        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)  # 自动调整列宽
        layout.addWidget(self.table)
        self._load_data()

    def _load_data(self):
        """从数据库加载数据"""
        from core.data_model import DataModel
        data_model = DataModel()
        self.data = data_model.get_data(self.well_name)
        if self.data is not None:
            self._update_table()
            # 发送数据更新信号
            self.data_updated.emit(self.well_name, self.data)

    def _update_table(self):
        """更新表格显示"""
        if self.data is not None:
            self.table.setColumnCount(len(self.data.columns))
            self.table.setHorizontalHeaderLabels(self.data.columns)
            self.table.setRowCount(len(self.data))
            
            for row in range(len(self.data)):
                for col in range(len(self.data.columns)):
                    value = str(self.data.iloc[row, col])
                    item = QTableWidgetItem(value)
                    item.setTextAlignment(Qt.AlignCenter)  # 居中对齐
                    self.table.setItem(row, col, item)

    def _load_sample_data(self):
        # 示例数据（当文件加载失败时使用）
        headers = ["A", "B", "C"]
        data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
        self.table.setColumnCount(len(headers))
        self.table.setHorizontalHeaderLabels(headers)
        self.table.setRowCount(len(data))
        for row, row_data in enumerate(data):
            for col, value in enumerate(row_data):
                self.table.setItem(row, col, QTableWidgetItem(str(value))) 